/*
 * @Description: 移交数据组件，包含操作，列表等
 * @Author: Rfan
 * @Date: 2022-05-12 11:47:37
 * @LastEditTime: 2022-09-08 14:33:13
 */

import { useEffect, useState } from 'react';
import { fetchMetadata } from '@/api/metadata';
import { fetchFormByCoordinate } from '@/api/system';
import { jsonClone } from '@/utils';
import { useDescDesignContext } from '../contexts/DescDesignContext';
import { QUERY_METADATA_EDIT } from '@/view/system/Metadata/constants';
import { LeggoConfigs } from '@/components/form-builder';
import type { ICoordinate } from '@/interfaces/global';
import '@/components/form-builder/styles/configs.less';

const PageContent = () => {
  const { selectAT, selectLevel, addDescFormFunc, editDescFormFunc } = useDescDesignContext();
  const [list, setList] = useState([]);
  const [descForm, setDescForm] = useState<any>({});
  const [schema, setSchema] = useState<any>({});

  useEffect(() => {
    if (selectAT.id && selectLevel.level) {
      setDescForm({});
      setSchema({});
      const coordinate: ICoordinate = {
        atType: selectAT.atType,
        atCode: selectAT.atCode,
        level: selectLevel.level
      };
      const fieldQuery = {
        metadataFieldType: QUERY_METADATA_EDIT,
        coordinate
      };
      fetchFormByCoordinate(coordinate).then((res) => {
        console.log('get form', res.data);
        if (res.data && res.data.length > 0) {
          setDescForm(res.data[0]);
          setSchema(JSON.parse(res.data[0].formJson));
        }
      });
      fetchMetadata(fieldQuery).then((res) => {
        setList(res.data);
      });
    }
  }, [selectAT, selectLevel]);

  const postSchemaModelData = (schemaModel: any) => {
    console.log('发送schema～～～～～～', schemaModel, schemaModel.name);
    if (!schemaModel.name) {
      schemaModel.name = `${selectAT.atName}-${selectLevel.levelName}`;
    }

    if (descForm.id) {
      const params = jsonClone(descForm);
      params.formJson = JSON.stringify(schemaModel);
      editDescFormFunc(params).then((res: any) => {
        setDescForm(res);
        setSchema(schemaModel);
      });
    } else {
      const params: any = {
        archiveTypeId: selectAT.id,
        atType: selectAT.atType,
        atCode: selectAT.atCode,
        level: selectLevel.level
      };
      params.formJson = JSON.stringify(schemaModel);
      addDescFormFunc(params).then((res: any) => {
        setDescForm(res);
        setSchema(schemaModel);
      });
    }
  };

  return (
    <div>
      {selectLevel?.level && (
        <LeggoConfigs onGetSchemaModel={postSchemaModelData} fieldList={list} formSchema={schema} />
      )}
    </div>
  );
};

export default PageContent;
